﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using Needle.Bus.Configuration;
using Needle.Utils;

namespace Needle.Bus.Engine.Factories
{

    public class MessageHandlerFactory : IFactory<IMessageHandler>
    {

        BusConfiguration _busConfiguration;

        public MessageHandlerFactory(BusConfiguration busConfiguration)
        {
            if (busConfiguration == null)
                throw new ArgumentNullException("busConfiguration", "busConfiguration is null.");

            _busConfiguration = busConfiguration;
        }

        public IMessageHandler Create(string id)
        {
            MessageHandlerConfiguration handlerCfg = null;
            if (!_busConfiguration.MessageHandlers.TryGetValue(id,out handlerCfg))
                throw new ArgumentException("unknown messagehandler id: " + id,"id");

            Type handlerType = Types.GetType(handlerCfg.Type, true);

            var handler = (IMessageHandler)Activator.CreateInstance(handlerType);

            foreach(var kv in handlerCfg.Data)
            {
                var propDesc = TypeDescriptor.GetProperties(handler)[kv.Key];
                if (propDesc == null)
                    throw new ArgumentException("Invalid property name " + kv.Key + " in configuration of messagehandler " + id);
                var converter = TypeDescriptor.GetConverter(propDesc.PropertyType);
                propDesc.SetValue(handler, converter.ConvertFromString(kv.Value));
            }

            return handler;
        }

        public IList<IMessageHandler> CreateAll()
        {
            throw new NotSupportedException();
        }
    }
}
